/**
 * 
 */
package com.nextive.interview.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.nextive.interview.R;
import com.nextive.interview.dao.WeightInfoDao;
import com.nextive.interview.service.WeightInfoService;
import com.nextive.interview.service.impl.WeightInfoServiceImpl;

/**
 * @author Martin
 *
 */
public class EditWeightEntryActivity extends Activity {
	
	private Long weightEntryId;
	
	private EditText weightText;
	private EditText dateText;
	private Button confirmButton;
	
	private WeightInfoService userInfoService;
	
	public EditWeightEntryActivity() {
		
		this.userInfoService = new WeightInfoServiceImpl(this);
		
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.weight_edit);
		bindInputs();
		
		weightEntryId = (savedInstanceState == null) ? null : 
			(Long) savedInstanceState.getSerializable(WeightInfoDao.ID_KEY);
		
		if (weightEntryId == null) {
			
			Bundle extras = getIntent().getExtras();
			weightEntryId = (Long) extras.getSerializable(WeightInfoDao.ID_KEY);
			
		}
		
		populateWeightInfo();
		
		confirmButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
			
				// there is no need to save anything since is being handled by onPause()
				setResult(RESULT_OK);
				finish();
				
			}
		});
		
	}

	// TODO - Check if we have to save the entry if we didn't complete all fields.
	// in here, if we happen to close the app or exit the app we save a partial entry
	// what do we do then ? default date and default weight ?
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		
		super.onSaveInstanceState(outState);
		savePartialState();
		outState.putSerializable(WeightInfoDao.ID_KEY, weightEntryId);
	}
    
    @Override
	protected void onPause() {
    	
		super.onPause();
		savePartialState();
		
	}

	@Override
	protected void onResume() {
		super.onResume();
		populateWeightInfo();
	}

	private void savePartialState() {
    	
    	if (weightEntryId == null) {
    		
    		// create a new weight entry
    		// TODO - add parameters to save the actual entry !!!
    		weightEntryId = userInfoService.createNewWeightEntry();
    		
    	} else {
    		
    		userInfoService.updateWeightInfo();
    		
    	}
    }
	
	// TODO - populate all info needed !
	private void populateWeightInfo() {
		
	}

	/**
	 * It binds all inputs to member fields so they can be referenced later on.
	 */
	private void bindInputs() {
		
		weightText = (EditText) findViewById(R.id.weight);
		dateText = (EditText) findViewById(R.id.date);
		confirmButton = (Button) findViewById(R.id.confirm);
		
	}

}
